/*
 * encPacketHandler.h
 *
 * Created: 6/13/2013 3:02:03 AM
 *  Author: Tim
 */ 


#ifndef ENCPACKETHANDLER_H_
#define ENCPACKETHANDLER_H_

#include <stdbool.h>
#include "../status.h"
#include "../../features/tmr/tmr.h"
#include <avr/io.h>

#include "../structs/encPacketStructs.h"

#include "../../features/enc/enc.h"

#include "../../features/tmr/tmr.h"

#include "../CRC.h"

#include "../structs/msgHeaderDefs.h"

#include "../../communication/comPort.h"

#include "../../board/board.h"

#include "genPacketHandler.h"

// may want to ensure there is no way to re-alloc the same encoder


static inline status_t encInitHandler(encInit_t *packet)
{

	//make sure the pin locations are available for an encoder
	if(encCheckPLOC(packet->PARAM1.PLOC,packet->PARAM1.INDX) == OPP_FAILED)				
	{
		sendGenAck(encInit_mh,0);
		return OPP_FAILED;
	}
	if(packet->PARAM1.ENCN)
	{
		if(daqAlloc.timerAlloc.timerC1Alloc == FEATURE_UTILIZED)						
		{
			sendGenAck(encInit_mh,0);	
			return OPP_FAILED;
		}
		else
		{
			allocTimer(TIMER_C1);
			encSetup	(	1												,
							packet->PARAM1.PLOC								,
							packet->PARAM1.INDX								,
							packet->PARAM2.ABS								,
							packet->PARAM2.EDFL								,
							(packet->PARAM2.ERESH<<8) | packet->PARAM3.ERESL
						);			
		}
	}
	else
	{
		if(daqAlloc.timerAlloc.timerC0Alloc == FEATURE_UTILIZED)						
		{
			sendGenAck(encInit_mh,0);
			return OPP_FAILED;
		}
		else
		{
			allocTimer(TIMER_C0);
			encSetup	(	0												,
							packet->PARAM1.PLOC								,
							packet->PARAM1.INDX								,
							packet->PARAM2.ABS								,
							packet->PARAM2.EDFL								,
							(packet->PARAM2.ERESH<<8) | packet->PARAM3.ERESL
						);
		}
	}
	
	sendGenAck(encInit_mh,(0x80 | 1<<packet->PARAM1.ENCN));
	return OPP_SUCCESSFUL;
}

#endif /* ENCPACKETHANDLER_H_ */